package com.henry.db.migrate.config;


import com.henry.db.migrate.util.XmlUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

public class Config {
    private static final String CONFIG_PATH = "cfg/config.xml";
    private static DbConfig srcDbConfig;
    private static DbConfig targetDbConfig;

    static {
        try {
            Document document = XmlUtil.loadXml(CONFIG_PATH);
            srcDbConfig = initDbConfig(document, "/root/src");
            targetDbConfig = initDbConfig(document, "/root/target");

        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

    private static DbConfig initDbConfig(Document document, String path) {
        Element srcNode = (Element) document.selectSingleNode(path);
        String driver = srcNode.attributeValue("driver");
        String url = srcNode.attributeValue("url");
        String username = srcNode.attributeValue("user");
        String password = srcNode.attributeValue("password");
        String pooled = srcNode.attributeValue("pooled");
        String poolsize = srcNode.attributeValue("poolsize");
        DbConfig dbConfig = new DbConfig(driver, url, username, password);
        dbConfig.setPooled(Boolean.parseBoolean(pooled));
        if (dbConfig.isPooled())
            dbConfig.setPoolsize(Integer.parseInt(poolsize));
        return dbConfig;
    }

    public static DbConfig getDbConfig(String name) {
        if ("src".equals(name))
            return srcDbConfig;
        else if ("target".equals(name))
            return targetDbConfig;
        throw new RuntimeException("没有对应的数据库配置");
    }

}
